package main
import (
	"encoding/json"
	"github.com/coreos/etcd/clientv3"
	etcdnaming "github.com/coreos/etcd/clientv3/naming"
	"google.golang.org/grpc/naming"

	"google.golang.org/grpc"
	"grpc_etcd/proto"
	"time"
	"context"
	"fmt"
)
/**
grpc官方resolver,wtacher方式实现负载均衡
注意：为github.com/coreos/etcd/clientv3包下的相关api
地址：https://etcd.io/docs/v3.4.0/dev-guide/grpc_naming/
 */
func main() {
	conf := clientv3.Config{Endpoints:[]string{"http://localhost:2379"}}
	cli, cerr := clientv3.New(conf)
	if cerr!=nil {
		panic(cerr)
	}
	r := &etcdnaming.GRPCResolver{Client: cli}
	b := grpc.RoundRobin(r)

	//系列化封装的服务地址值,put to etcd
	a0 := naming.Update{Op:naming.Add,Addr:"127.0.0.1:8080"}
	a1 := naming.Update{Op:naming.Add,Addr:"127.0.0.1:8081"}
	byte0,_ := json.Marshal(a0)
	byte1,_ := json.Marshal(a1)
	cli.Put(context.TODO(),"my-service_127.0.0.1:8080",string(byte0))
	cli.Put(context.TODO(),"my-service_127.0.0.1:8081",string(byte1))

	conn, gerr := grpc.DialContext(context.TODO(),"my-service", grpc.WithInsecure(), grpc.WithBalancer(b), grpc.WithBlock())
	if gerr!=nil{
		panic(gerr)
	}
	t := time.NewTicker(2 * time.Second)
	for tc := range t.C {
		//请求rpc服务
		client := proto.NewStudentServerClient(conn)
		student,err := client.GetStudent(context.TODO(),&proto.ReqStudent{Id:1})
		if err!=nil{
			panic(err)
			return
		}
		fmt.Println(student,"  ",tc)
	}
}
